const defaults = {
	method:"get"
}

class Axios {
	constructor(instanceConfig) {
		// 增加实例属性defaults,值为形参instanceConfig
		this.defaults = instanceConfig;
	}
	request(configOrUrl,config={}){
		// 判断第一个参数是否为字符串（判断第一个参数是否为url地址）
		if(typeof configOrUrl === "string"){
			config.url = configOrUrl;
		}else{
			config = configOrUrl;
		}
		// 将this.defaults与config进行合并，结果赋值给config.
		config = {
			...this.defaults,
			...config
		};
		// 发送请求的
		const dispatchRequest = function(){
			return new Promise((resolve,reject)=>{
				const request = new XMLHttpRequest();
				request.responseType = "json";
				request.open(config.method,config.url);
				request.send();
				request.onload = function(){
					resolve({
						config,
						headers:request.getAllResponseHeaders(),
						data:request.response,
						request,
						status:request.status,
						statusText:request.statusText
					})
				}
			})
		}
		return dispatchRequest.call(this);
	}
}

function createInstance(defaultConfig) {
	// 创建一个Axios实例
	const context = new Axios(defaultConfig);
	// 调用axios的本质是调用instance,instance的本质是：Axios.prototype.request
	const instance = Axios.prototype.request.bind(context);
	return instance;
}

const axios = createInstance(defaults);
export default axios;